package view.models;

import java.util.List;
import java.util.Observable;
import java.util.Observer;

import javax.swing.table.AbstractTableModel;

import domain.Customer;
import domain.Library;

@SuppressWarnings("serial")
public class CustomerTable extends AbstractTableModel implements Observer {
	Library lib = Library.getInstance();
	List<Customer> customers;
//	DateFormat localizeDate = DateFormat.getDateInstance();
	private String[] columnNames = new String[]{"Status", "Vorname", "Name", "Addresse", "Postleitzahl", "Ort"};
	private int[] searchColumns = {0,1,2,3,4};
	
	public CustomerTable() {
		customers = lib.getCustomers();
		for (Customer c : customers) {
			c.addObserver(this);
		}
		lib.addObserver(this);
	}

	@Override
	public int getColumnCount() {
		return columnNames.length;
	}

	@Override
	public int getRowCount() {
		return customers.size();
	}
	
	@Override
	public String getColumnName(int col){
		return columnNames[col];
	}
	
	public int[] getSearchColumns(){
		return searchColumns;
	}

	@Override
	public Object getValueAt(int row, int col) {
		Customer customer = customers.get(row);
		switch (col) {
			case 0:
				return CustomerStatus.getInstanceOf(customer);
			case 1 : // Vorname
				return customer.getSurname();
			case 2:	// name
				return customer.getName();
			case 3: // Strasse
				return customer.getStreet();
			case 4: // PLZ
				return customer.getZip();
			case 5:	// Stadt
				return customer.getCity();
		}
		return null;
	}

	@Override
	public void update(Observable o, Object arg1) {
		if(arg1 instanceof Customer){
			Customer buffer = (Customer)arg1;
			buffer.addObserver(this);
		}
		fireTableDataChanged();
	}

	public Customer getCustomerAt(int row) {
		return customers.get(row);
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Class getColumnClass(int c) {
		switch(c){
			case 0:
				return CustomerStatus.class;
			case 4:
				return Integer.class;
			default:
				return String.class;
		}
	}
	
	public void disbandObservers(){
		lib.deleteObserver(this);
		for(Customer c : lib.getCustomers()){
			c.deleteObserver(this);
		}
	}

}
